package com.my.zl.console.service.base;

import java.io.File;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.my.zl.common.dto.ReqDTO;
import com.my.zl.common.dto.ResDTO;
import com.my.zl.common.dto.advancedQuery.PageQueryDTO;
import com.my.zl.common.enums.resp.GlobalEnum;
import com.my.zl.common.enums.resp.RespEnum;
import com.my.zl.common.exception.BizException;
import com.my.zl.common.utils.PageUtil;
import com.my.zl.common.utils.ReturnUtil;
import com.my.zl.console.common.config.MyselfProperties;
import com.my.zl.console.dao.base.SysBaseMapper;
import com.my.zl.console.entity.base.BaseTime;

import cn.hutool.core.util.StrUtil;

/**
 * 某些普遍方法再次封装，减少引入快速使用
 * @author zhouliang
 *
 */
public class BaseManager {

    protected final Logger LOGGER = LoggerFactory.getLogger(getClass());
    
    @Autowired
    private SysBaseMapper sysBaseMapper;
//    @Autowired
//    private RedisUtil redisUtil;
    @Autowired
    private MyselfProperties myselfProperties;
    
    /** 获取时间*/
    public BaseTime getSystemTime() {
        BaseTime timeVO = new BaseTime();
        try{
            timeVO = sysBaseMapper.selectSysCurrentTime();
        }catch(Exception e){
            timeVO.setUtcTime(Instant.now());
        }
        timeVO.setDataTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                .withLocale(Locale.SIMPLIFIED_CHINESE).withZone(ZoneId.of("+08:00")).format(timeVO.getUtcTime()));
        timeVO.setDateDay(timeVO.getDataTime().substring(0, 10));
        return timeVO;
    }
    
    /**
     * 数字自增主键，顺序+1
     * key: hash名称 
     * item: hash成员名称
     * */
/*    public Long redisHashKey(String item) {
        long autokey = redisUtil.hincr(AutocodeKeyC.AUTO_TABLE_KEY, item, 1L);
        if(autokey <= 0L){//超过当前主键长度范围
            throw new BizException(GlobalEnum.ERROR_PRIMARY_KEY);
        }
        return autokey;
    }
    
    public void redisHSetJson(String item,Object obj) {
        redisUtil.hset(AutocodeRedisC.ZL_JSON_KEY, item, JSONObject.toJSONString(obj), 0);
    }
    
    public <T> T redisHGetJson(String item, Class<T> cls) {
       Object val = redisUtil.hget(AutocodeRedisC.ZL_JSON_KEY, item);
       if(val != null){
           return JSONObject.parseObject(val.toString(), cls);
       }
       return null;
    }
    
    public void redisSetJson(String item,Object obj) {
        redisUtil.set(item, JSONObject.toJSONString(obj), 3600);
    }
    
    public <T> T redisGetJson(String item, Class<T> cls) {
        Object val = redisUtil.get(item);
        if(val != null){
            return JSONObject.parseObject(val.toString(), cls);
        }
        return null;
    }*/
    
    /** 
     * 处理分页属性，校验正确性
     */
    public static void pageHandle(PageQueryDTO page) {
        PageUtil.pageHandle(page);
    }
    
    /**
     * 返回成功
     */
    public static <T> ResDTO<T> successDATA(T data){
        return ReturnUtil.successDATA(data);
    }
    /**
     * 返回失败
     */
    public static <T> ResDTO<T> errorDATA(T data){
        return ReturnUtil.errorDATA(data);
    }
    /**
     * 自定返回
     */
    public static <T> ResDTO<T> returnDATA(RespEnum code,T data){
        return ReturnUtil.returnDATA(code,data);
    }
    
    
    /** 更新关键字段*/
    public <T> void initUpdateInfo(T info, ReqDTO<?> reqInfo, Instant time) {
        try{
            Class<?> clz = info.getClass();
            clz.getMethod("setLastUpdName", String.class).invoke(info, reqInfo.getReqUserName());
            clz.getMethod("setLastUpdOprid", String.class).invoke(info, reqInfo.getReqUserId());
            clz.getMethod("setLastUpdTm", Instant.class).invoke(info, time);
        }catch(Exception e){
        }
    }
    
    /** 创建关键字段*/
    public <T> void initCreateInfo(T info, ReqDTO<?> reqInfo, Instant time) {
        try{
            Class<?> clz = info.getClass();
            clz.getMethod("setCreateName", String.class).invoke(info, reqInfo.getReqUserName());
            clz.getMethod("setCreateOprid", String.class).invoke(info, reqInfo.getReqUserId());
            clz.getMethod("setCreateTm", Instant.class).invoke(info, time);
            initUpdateInfo(info, reqInfo, time);
        }catch(Exception e){
        }
    }
    
    
    /** 组装文件路径*/
    public static String filePath(String mainRoot, String mainPath, String mainPath2, String[] otherPaths){
        boolean isWindows = System.getProperty("os.name").toLowerCase().contains("win");
        String separatorStr = File.separator;
        
        //不能丢失目录，否则会会删除目录下的文件
        if(StringUtils.isBlank(mainPath) || StringUtils.isBlank(mainPath2)){
            throw new BizException(GlobalEnum.MISSING_FILE.getCode(), GlobalEnum.MISSING_FILE.getMsg());
        }
        
        String extpath = "";
        if(otherPaths != null){
            for(String pathx : otherPaths){
                if(pathx.contains("---")){
                    String[] tp = pathx.split("---");
                    if(tp[0].length()<Integer.valueOf(tp[1])){
                        pathx = StrUtil.padPre(tp[0], Integer.valueOf(tp[1]), "0");
                    }else{
                        pathx = tp[0];
                    }
                }
                extpath = extpath + pathx + separatorStr;
            }
        }
        
        mainPath = mainPath.replaceAll("(\\\\)+", "/");
        String oldMainPath = mainPath;
        if(mainPath.startsWith("/")){
            mainPath = mainPath.replaceFirst("(/)+", "");
        }
        if(!mainPath.endsWith("/")){
            mainPath = mainPath + "/";
        }
        if(mainPath2.startsWith("/")){
            mainPath2 = mainPath2.replaceFirst("(/)+", "");
        }
        if(!mainPath2.endsWith("/")){
            mainPath2 = mainPath2 + "/";
        }
        mainPath = mainPath + mainPath2;
        
        if(StringUtils.isNotBlank(mainRoot)){
            mainPath = mainRoot +'/'+ mainPath + extpath;
        }
        if(StringUtils.isBlank(mainRoot)){
            if(isWindows){
                File[] roots = File.listRoots();
                boolean flag = false;
                for (int i =0; i < roots.length; i++) {
                   String tmp = roots[i] + oldMainPath;
                   File f = new File(tmp);
                   if(f.exists() && f.isDirectory()){
                       flag = true;
                       mainPath = roots[i] + mainPath + extpath;
                       break;
                   }
                }
                if(!flag){
                    mainPath = roots[roots.length-1] + mainPath + extpath;
                }
            }else{
                String[] roots = {"/home/","/usr/","/root","/tmp","/home/user"};
                String tmp1 = roots[0] + oldMainPath;
                File f = new File(tmp1);
                if(f.exists() && f.isDirectory()){
                    mainPath = tmp1 + extpath;
                }else{
                    tmp1 = roots[1] + mainPath;
                    f = new File(tmp1);
                    if(f.exists() && f.isDirectory()){
                        mainPath =  tmp1 + extpath;
                    }else{
                        mainPath = roots[0] + mainPath + extpath;
                    }
                }
            }
        }
        
        mainPath = mainPath.replaceAll("(\\\\)+", "/");
        mainPath = mainPath.replaceAll("(/)+", "/");
        return mainPath;
    }
 }